﻿using Devonline.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Devonline.AspNetCore.OData;

/// <summary>
/// 基于 OData 和 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext">数据库上下文</typeparam>
/// <typeparam name="TEntitySet">业务数据类型</typeparam>
/// <typeparam name="TKey">主键类型</typeparam>
[Authorize]
[ApiController]
[Route("api/[controller]")]
public abstract class ODataServiceController<TDbContext, TEntitySet, TKey> :
    DataServiceController<TDbContext, TEntitySet, TKey>
    where TDbContext : DbContext
    where TEntitySet : class, IEntitySet<TKey>
    where TKey : IConvertible
{
    public ODataServiceController(
        ILogger<ODataServiceController<TDbContext, TEntitySet, TKey>> logger,
        IDataService<TDbContext, TEntitySet, TKey> dataService
        ) : base(logger, dataService) { }

    /// <summary>
    /// 使用 odata 协议进行查询的 get 请求
    /// </summary>
    /// <returns></returns>
    [HttpGet, EnableQuery]
    public virtual IActionResult Get() => Ok(_dataService.GetQueryable());
}

/// <summary>
/// 基于字符串作为主键的 OData 和 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext">数据库上下文</typeparam>
/// <typeparam name="TEntitySet">业务数据类型</typeparam>
[Authorize]
[ApiController]
[Route("api/[controller]")]
public abstract class ODataServiceController<TDbContext, TEntitySet> :
    DataServiceController<TDbContext, TEntitySet>
    where TDbContext : DbContext
    where TEntitySet : class, IEntitySet<string>
{
    public ODataServiceController(
        ILogger<ODataServiceController<TDbContext, TEntitySet>> logger,
        IDataService<TDbContext, TEntitySet> dataService
        ) : base(logger, dataService) { }

    /// <summary>
    /// 使用 odata 协议进行查询的 get 请求
    /// </summary>
    /// <returns></returns>
    [HttpGet, EnableQuery]
    public virtual IActionResult Get() => Ok(_dataService.GetQueryable());
}